﻿#include "local_server.h"

local_server::local_server(QString listen_name)
{
     this->listen_name=listen_name;
     qRegisterMetaType<emit_type>("emit_type");
}


bool local_server::start_server()
{
    if(!listen(listen_name))
    {
        qDebug()<<"本地监听失败!";
        return false;
    }
    else
    {
        qDebug()<<"本地监听成功!";
        return  true;
    }
}


void local_server::incomingConnection(quintptr socketDescriptor)
{
    qDebug()<<"本地计算模块连接成功!";
   local_socket *l_socket=new local_socket(socketDescriptor);
    if(!l_socket->localSocket_init())
    {
        return;
    }
    l_socket->send_message("服务器","获取程序类型","");



    QSharedPointer<M_Socket>   msocket=QSharedPointer<M_Socket>(new M_Socket());
    msocket.data()->Stype=Lsocket;
    msocket.data()->l_socket=l_socket;

    Common::localSocket_MapLock.lockForWrite();
    Common::localSocket_Map[l_socket]=msocket;
    Common::localSocket_MapLock.unlock();
    connect(l_socket,SIGNAL(disconnected()),this,SLOT(delete_localSocket()),Qt::QueuedConnection);
    connect(l_socket,SIGNAL(reply_data(QString,QString,QString)),handlemanage.data(),SLOT(receive(QString,QString,QString)),Qt::QueuedConnection);
    connect(handlemanage.data(),SIGNAL(l_SocketSendData(QString,QString,QString,local_socket*,emit_type,QString)),l_socket,SLOT(l_socketSend(QString,QString,QString,local_socket*,emit_type,QString)),Qt::QueuedConnection);


}

void local_server::delete_localSocket()
{
    qDebug()<<"本地计算模块断开连接";
    local_socket *socket=qobject_cast<local_socket*>(sender());
    Common::localSocket_MapLock.lockForWrite();
    if(Common::localSocket_Map.remove(socket)==0)
    {
        qDebug()<<"没有在map中找到localsocket!!";
    }
     Common::localSocket_MapLock.unlock();
     emit this->restart_localcaculate();
}

void local_server::set_handle(QWeakPointer<handle_manage> handlemanage)
{
    if(handlemanage.isNull())
    {
        qDebug()<<"处理线程未初始化";
    }
    this->handlemanage=handlemanage;
}
